import { z } from 'zod';
import { router } from '../trpc';
import { adminProcedure } from '../middleware';
import { createSuccessResponse, createErrorResponse } from '../../utils/response';
import { PaymentChannel } from '@prisma/client';
import { paymentService } from '../../services/paymentService';
import { channelConfigService } from '../../services/channelConfigService';

// Input validation schemas
const updateChannelConfigSchema = z.object({
  channel: z.nativeEnum(PaymentChannel),
  config: z.object({
    weight: z.number().min(0).max(999999).optional(),
    isEnabled: z.boolean().optional(),
    minAmount: z.number().min(0).optional(),
    maxAmount: z.number().min(1).optional(),
    dailyLimit: z.number().min(0).optional(),
    priority: z.number().min(1).optional(),
    channelName: z.string().optional(),
    displayName: z.string().optional(),
  })
});

const batchUpdateWeightsSchema = z.object({
  weights: z.record(z.string(), z.number().min(0).max(999999))
});

const testChannelSelectionSchema = z.object({
  amount: z.number().positive('测试金额必须大于0'),
  testCount: z.number().int().min(10).max(10000).default(100)
});

export const channelConfigRouter = router({
  /**
   * 获取所有渠道配置
   */
  getChannelConfigs: adminProcedure
    .query(async () => {
      try {
        const config = paymentService.getChannelWeightConfig();
        const availableChannels = paymentService.getAvailableChannels();

        // 添加渠道可用性信息
        const channelsWithAvailability = Object.entries(config.channels).map(([channel, channelConfig]) => ({
          channel,
          ...channelConfig,
          isConfigured: paymentService.isChannelConfigured(channel as PaymentChannel),
          isAvailable: availableChannels.includes(channel as PaymentChannel)
        }));

        return createSuccessResponse({
          ...config,
          channelsWithAvailability,
          availableChannels
        }, '获取渠道配置成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '获取渠道配置失败',
          'GET_CHANNEL_CONFIG_ERROR'
        );
      }
    }),

  /**
   * 更新单个渠道配置
   */
  updateChannelConfig: adminProcedure
    .input(updateChannelConfigSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        await paymentService.updateChannelConfig(input.channel, input.config);

        // 记录操作日志
        console.log(`管理员 ${ctx.user.username} 更新了渠道 ${input.channel} 的配置`, {
          userId: ctx.user.userId,
          channel: input.channel,
          config: input.config
        });

        return createSuccessResponse(null, '渠道配置更新成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '更新渠道配置失败',
          'UPDATE_CHANNEL_CONFIG_ERROR'
        );
      }
    }),

  /**
   * 批量更新渠道权重
   */
  batchUpdateWeights: adminProcedure
    .input(batchUpdateWeightsSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const weights: Record<PaymentChannel, number> = {
          [PaymentChannel.TOPPAY]: input.weights.TOPPAY || 0,
          [PaymentChannel.PAY668]: input.weights.PAY668 || 0,
          [PaymentChannel.LSPPAY]: input.weights.LSPPAY || 0,
          [PaymentChannel.HUIFENG]: input.weights.HUIFENG || 0,
          [PaymentChannel.NASKI]: input.weights.NASKI || 0
        };
        await paymentService.batchUpdateWeights(weights);

        // 记录操作日志
        console.log(`管理员 ${ctx.user.username} 批量更新了渠道权重`, {
          userId: ctx.user.userId,
          weights: input.weights
        });

        return createSuccessResponse(null, '渠道权重批量更新成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '批量更新渠道权重失败',
          'BATCH_UPDATE_WEIGHTS_ERROR'
        );
      }
    }),

  /**
   * 测试渠道选择算法
   */
  testChannelSelection: adminProcedure
    .input(testChannelSelectionSchema)
    .query(async ({ input }) => {
      try {
        const testResult = paymentService.testChannelSelection(input.amount, input.testCount);
        
        // 计算理论概率（基于权重）
        const config = paymentService.getChannelWeightConfig();
        const availableChannels = paymentService.getAvailableChannels();
        
        const eligibleChannels = availableChannels.filter(channel => {
          const channelConfig = config.channels[channel];
          return channelConfig?.isEnabled &&
                 input.amount >= channelConfig.minAmount &&
                 input.amount <= channelConfig.maxAmount;
        });

        const theoreticalPercentages: Record<string, number> = {};
        if (testResult.totalWeight > 0) {
          eligibleChannels.forEach(channel => {
            const weight = config.channels[channel].weight;
            theoreticalPercentages[channel] = (weight / testResult.totalWeight) * 100;
          });
        }

        return createSuccessResponse({
          ...testResult,
          theoreticalPercentages,
          eligibleChannels
        }, '渠道选择测试完成');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '渠道选择测试失败',
          'TEST_CHANNEL_SELECTION_ERROR'
        );
      }
    }),

  /**
   * 获取单次渠道选择结果（用于实时测试）
   */
  selectChannel: adminProcedure
    .input(z.object({
      amount: z.number().positive('金额必须大于0')
    }))
    .query(async ({ input }) => {
      try {
        const selection = paymentService.selectOptimalChannel(input.amount);
        return createSuccessResponse(selection, '渠道选择成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '渠道选择失败',
          'SELECT_CHANNEL_ERROR'
        );
      }
    }),

  /**
   * 重置为默认配置
   */
  resetToDefault: adminProcedure
    .mutation(async ({ ctx }) => {
      try {
        await channelConfigService.resetToDefault();

        // 记录操作日志
        console.log(`管理员 ${ctx.user.username} 重置了渠道配置为默认值`, {
          userId: ctx.user.userId
        });

        return createSuccessResponse(null, '渠道配置已重置为默认值');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '重置配置失败',
          'RESET_CONFIG_ERROR'
        );
      }
    }),

  /**
   * 强制重新加载配置
   */
  reloadConfig: adminProcedure
    .mutation(async ({ ctx }) => {
      try {
        const config = channelConfigService.reloadConfig();

        // 记录操作日志
        console.log(`管理员 ${ctx.user.username} 重新加载了渠道配置`, {
          userId: ctx.user.userId
        });

        return createSuccessResponse(config, '配置重新加载成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '重新加载配置失败',
          'RELOAD_CONFIG_ERROR'
        );
      }
    }),

  /**
   * 获取渠道状态统计
   */
  getChannelStats: adminProcedure
    .query(async () => {
      try {
        const config = paymentService.getChannelWeightConfig();
        const availableChannels = paymentService.getAvailableChannels();

        const stats = {
          totalChannels: Object.keys(config.channels).length,
          enabledChannels: Object.values(config.channels).filter(c => c.isEnabled).length,
          configuredChannels: availableChannels.length,
          totalWeight: Object.values(config.channels)
            .filter(c => c.isEnabled)
            .reduce((sum, c) => sum + c.weight, 0),
          lastUpdated: config.lastUpdated,
          version: config.version
        };

        return createSuccessResponse(stats, '获取渠道统计成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '获取渠道统计失败',
          'GET_CHANNEL_STATS_ERROR'
        );
      }
    }),
});